"""
    从阿里云oss下载文件到本地
    在阿里云服务器上跑，走内网不产生外网流量
"""
import oss2
import environ
import os
import sys
import django

ROOT_DIR = (
        environ.Path(__file__) - 2
)
sys.path.append(str(ROOT_DIR))
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings.local')
django.setup()


def downloadCompanyAnswerFile():
    """ 下载企业在小程序上的现场图片 """
    access_key_id = 'LTAI5tPZQKcCP1RvoCs4kgUw'
    access_key_secret = 'C2xELYe9H4TJ9OBRtNT2u9PMADj4SH'
    auth = oss2.Auth(access_key_id, access_key_secret)

    endpoint = 'https://oss-cn-shenzhen-internal.aliyuncs.com'
    bucket_name = 'humen-pollution'
    bucket = oss2.Bucket(auth, endpoint, bucket_name)

    from apps.pollution.models import Answer
    qs = Answer.objects.all().values('company_name', 'images')
    for i in qs:
        company_name = i['company_name']
        for file_path in i['images']:
            file_name = file_path.replace('company/', '')
            # 路径不存在则创建相应的文件夹
            download_to_dir_path = f"{str(ROOT_DIR)}/media/answer/{company_name}/"
            if not os.path.exists(download_to_dir_path):
                os.makedirs(download_to_dir_path)
            download_to = f"{str(ROOT_DIR)}/media/answer/{company_name}/{file_name}"
            bucket.get_object_to_file(file_path, download_to)
            print(f'成功下载 {file_name}')


def downloadCompanySelfAss():
    """ 下载企业在网页端自评的文件 """
    access_key_id = 'LTAI5tPZQKcCP1RvoCs4kgUw'
    access_key_secret = 'C2xELYe9H4TJ9OBRtNT2u9PMADj4SH'
    auth = oss2.Auth(access_key_id, access_key_secret)

    endpoint = 'https://oss-cn-shenzhen-internal.aliyuncs.com'
    bucket_name = 'humen-pollution'
    bucket = oss2.Bucket(auth, endpoint, bucket_name)

    from apps.pollution.models import CompanySelfAssessment
    from apps.common.account.models import Account
    need_company_qs = Account.objects.filter(is_company=True, is_analysis=True).values_list("username", flat=True)
    qs = CompanySelfAssessment.objects.filter(company_name__in=need_company_qs).values()
    for i in qs:
        company_name = i['company_name']

        # 下载自评表
        for file_path in i['self_assessment_table']:

            download_to_dir_path = f"{str(ROOT_DIR)}/media/self_ass/{company_name}/自评表/"
            if not os.path.exists(download_to_dir_path):
                os.makedirs(download_to_dir_path)

            file_name_lst = file_path.split('-')
            file_name = '-'.join(file_name_lst[2:])
            download_to = f"{str(ROOT_DIR)}/media/self_ass/{company_name}/自评表/{file_name}"
            bucket.get_object_to_file(file_path, download_to)
            print(f'成功下载 {file_name}')

        # 下载指标1到8
        zh_dict = {
            1: '指标1.符合项目选址及产业政策要求',
            2: '指标2.废水、废气、噪声达标排放',
            3: '指标3.无组织废气排放管控',
            4: '指标4.开展固体废物规范化管理',
            5: '指标5.开展环境风险应急综合整治',
            6: '指标6.开展信息化管理建设',
            7: '指标7.达到环境管理综合要求',
            8: '指标8.采用污染防治可行技术',
        }
        for num in range(1, 9):
            files = []
            for file_lst in i[f'category_{num}'].values():
                files.extend(file_lst)

            for file_path in files:

                download_to_dir_path = f"{str(ROOT_DIR)}/media/self_ass/{company_name}/{zh_dict[num]}"
                if not os.path.exists(download_to_dir_path):
                    os.makedirs(download_to_dir_path)

                file_name_lst = file_path.split('-')
                file_name = '-'.join(file_name_lst[2:])
                download_to = f"{str(ROOT_DIR)}/media/self_ass/{company_name}/{zh_dict[num]}/{file_name}"
                bucket.get_object_to_file(file_path, download_to)
                print(f'成功下载 {file_name}')


if __name__ == '__main__':
    # downloadCompanyAnswerFile()
    downloadCompanySelfAss()
